package emas.server.authentication;

import java.sql.ResultSet;
import java.sql.SQLException;

import emas.server.core.MySQLConnectionManager;
import emas.server.encrypt.BCrypt;
import emas.shared.SQLConstants;

public class AuthenticationManager {
	private static AuthenticationManager instance = new AuthenticationManager();

	private AuthenticationManager() {

	}

	public static boolean isUserAuthenticated(String username, String password) {
		boolean isAuthenticated = false;

		String hashedpw = getHashedPWForUser(username);
		isAuthenticated = BCrypt.checkpw(password, hashedpw);

		return isAuthenticated;
	}

	private static String getHashedPWForUser(String username) {
		String hashpassword = null;
		MySQLConnectionManager mySQLConnectionManager = MySQLConnectionManager
				.getInstance();
		ResultSet resultSet = mySQLConnectionManager
				.selectQuery("SELECT HASHPASSWORD FROM "+SQLConstants.user_table+" WHERE USERNAME='"
						+ username + "'");

		try {
			if (resultSet != null) {
				resultSet.next();
				hashpassword = resultSet.getString("HASHPASSWORD");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return hashpassword;
	}

	public static AuthenticationManager getInstance() {
		if (instance == null) {
			instance = new AuthenticationManager();
		}
		return instance;
	}
}
